package com.laiyizhan.common.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 * Created by folie on 2016/12/22.
 */
public class LoginInterceptor implements HandlerInterceptor {

    private String loginUrl = "/login.jsp";
    private String reqLogin = "/admin/manager/login";

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、请求到登录页面 放行

        if (request.getServletPath().startsWith(reqLogin)) {
            return true;
        }

        //2、如果用户已经登录 放行
        if (request.getSession().getAttribute("adminUser") != null) {
            return true;
        }

        log.info("未登录, 跳转登录页面");
        //3、非法请求 即这些请求需要登录后才能访问
        //重定向到登录页面
        response.sendRedirect(request.getContextPath() + loginUrl);
        return false;
    }
}
